/** 
 * @description 支持单个图片选择控件，仅支持【本地选择图片】，不支持【从服务端选择图片】
 * @description 本控件不支持将从本地选择的图片上传至服务端，通过属性file和方法getFile,将已选择的文件返回给使用者
 * */
Rsd.define('Rsd.form.Image', {
    extend: 'Rsd.control.Component',
    xtype: 'image',
    ctrlTagName: 'div',
    ctrlCls: 'x-control-image',
    dataIndex: '',
    height:140,
    /**
    * 图地址,
    * 与value的区别是：
    *   src不做任何转换，直接将值设在img元素的src属性上， 
    *   value 值可通过formatString进行格式化后设置到img元素的src属性上，不会干扰 value 的获取
    * */
    src: '',
    /**
     * 通过格式化字符串，为src 追加配置参数，且不影响value返回
     * 如：
     * 格式1:"https://image.sellerpartner.cn/{{=value}}?x-oss-process=image/resize,h_100,m_lfit"
     * 格式2:"{{=value}}?x-oss-process=image/resize,h_100,m_lfit"
     */
    formatString:null,
    /**
    * @description 是否是只读模式：在只读模式下不能用于上传图片。
    * */
    readonly: true,
    /**
     * @description image/jpeg, image/x-png, image/gif
     * */
    accept: 'images/*',
    /**
     * 
     */
    border: false,
    /**
     * 控件的背景图片，false 或者 none 表示不设置背景图片
     */
    backgroundImage: false,
    /**
     * 显示加载进度条，多个图片布局在一个页面时 不适合使用 
     */
    showLoadingBar: false,
    /**
     * value is :server or local
     */
    from: 'server',
    /**
     * 仅from == 'server'，时有效
     */
    selectorServices: null,
    /**
     * @description 图片剪裁属性 
     * <取消注释 代码编辑会报错>
     */
    //clip:'',
    /**
     * @description 自定义 添加图片文件 事件 ，点击添加按钮时发生
     */
    onadd: null,
    /**
     * @description 自定义 删除当前图片文件 事件，点击删除按钮时发生
     */
    ondelete: null,
    /**
     * @description 自定义 本地文件选择 事件， 本地选择的文件发生改变时发生
     */
    onchange: null,
    /**
     * @description 单击图片时发生
     */
    onclick: '',
    /**
     * @description 选中 改变时发生
     */
    oncheckedchange:null,
    /**
     * 获取下载文件的名称
     */
    getFileNameHandler: null,
    /**
     * 抠图事件
     */
    showImageEditorHandler:'',
    /**
     * 本地已选择文件对象
     */
    file: null,
    /***
     * 展示toolbar 
     * 兼容小写属性名： toolbar 
     */
    //toolBar: {},
    /**
     * 展示 选择框
     */
    checkbox:false,
    /*
     * */
    constructor: function Image(config) {
        config = config || {}; 
        if(config.hasOwnProperty('toolbar') && !config.hasOwnProperty('toolBar') )
        {
            config.tooBar = config.toolbar;
        }
        this.apply(config || {});
    },

    /**
     * */
    initComponentEx: function initComponentEx() {

        this.callParent();
        //img dom 对象 存在跨越问题，加载优先级高，可被SEO抓取
        //background-image 可以避免跨越问题，但加载优先级靠后，不可被SEO抓取
        var _img = document.createElement('img');
        _img.crossOrigin = "anonymous";
        this.image = _img;
        if (this.border) {
            //边框效果:外围添加一个虚线边框
            var _border = document.createElement('div');
            _border.classList.add('x-border');
            _border.classList.add('x-control-image');
            this.ctrl.element.appendChild(_border);
            _border.appendChild(_img);
        }
        else {
            this.ctrl.element.appendChild(_img);
        }

        var me = this;
        me.image.style.maxWidth = '100%';
        me.image.style.maxHeight = '100%';

        //工具栏
        var _tb = me.toolBar; 

        if (_tb && _tb.visible) {
            var toolbar = document.createElement('div');
            toolbar.style.position = 'absolute';
            toolbar.style.backgroundColor = '#1b14141a';
            toolbar.style.display = 'flex';
            toolbar.style.flexDirection = 'column';
            toolbar.style.justifyContent = 'center';
            toolbar.style.alignItems = 'center';
            //console.log(me.toolbar.position);
            //
            switch (_tb.position) {
                case 'top':
                    {
                        toolbar.style.height = '10%';
                        toolbar.style.maxHeight = '50px';
                        toolbar.style.width = '100%';
                        toolbar.style.top = '0px';
                    }
                    break;
                case 'bottom':
                    {
                        toolbar.style.height = '10%';
                        toolbar.style.maxHeight = '50px';
                        toolbar.style.width = '100%';
                        toolbar.style.bottom = '0px';
                    }
                    break;
                case 'left':
                    { 
                        toolbar.style.width = '10%';
                        toolbar.style.maxWidth = '50px';
                        toolbar.style.height = '100%';
                        toolbar.style.left = '0px';
                    }
                    break;
                case 'right':
                default:
                    { 
                        toolbar.style.width = '10%';
                        toolbar.style.maxWidth = '50px';
                        toolbar.style.height = '100%';
                        toolbar.style.right = '0px';
                    }
                    break;
            }

            if(_tb.style)
            {
                me.setElStyle(toolbar,_tb.style);
            }
            me.ctrl.element.appendChild(toolbar);
            //console.log('--->',_tb.buttons);
            for (var i in _tb.buttons) {
                var btn = _tb.buttons[i];
                var svg = Rsd.create('Rsd.control.Svg', {
                    label: false,
                    tip: btn.title,
                    height: 30,
                    width: 30,
                    margin: '10 10 10 10',
                    cls: 'x-btn',
                    style: {
                        cursor: 'pointer',
                    },
                    parent: me,
                    handler: btn.handler

                });
                //console.log(btn);
                svg.loadData(btn.svg);
                svg.renderTo(toolbar);
                svg.doLayout();
                //toolbar.appendChild(zoomBtn.dom);
            }

        }
        
        if(me.onclick)
        {
            me.image.onclick = function (evt) { 
                me.funApplyByIOC(me.onclick, [me, evt]); 
            } 
        }
         
        this.image.onload = function () {
            me.image.style.display = 'inline-block';
            me.closeLoading();
        };

        this.image.onerror = function () {
            me.image.style.display = 'inline-block';
            me.closeLoading();
        };
        //修改 和 删除
        if (!this.readonly) {
            //删除按钮
            var _close = document.createElement('span');
            this.btnClose = _close;
            _close.appendChild(document.createTextNode('X'));
            _close.classList.add('x-close');
            _close.onclick = function (e) {
                me.setSrc('#');
                e.stopPropagation();
                me.funApplyByIOC(me.ondelete, [me, e]);
            }
            this.ctrl.element.appendChild(_close);

            var _add = document.createElement('div');
            this.btnAdd = _add;
            _add.classList.add('x-add');

            _add.style.top = this.ctrl.element.style.top;
            _add.style.right = this.ctrl.element.style.right;
            _add.style.bottom = this.ctrl.element.style.bottom;
            _add.style.left = this.ctrl.element.style.left;
            _add.style.width = this.ctrl.element.width;
            _add.style.height = this.ctrl.element.height;

            //自定义 添加文件  实现
            if (this.onadd) {
                _add.onclick = function (evt) {

                    me.funApplyByIOC(me.onadd, [me, evt]);
                }
            }
            else {
                if (this.from == 'local') {
                    var _file = document.createElement('input');
                    _file.type = 'file';
                    _file.style.width = "99%";
                    _file.style.height = "99%";
                    _file.style.opacity = 0;
                    _file.accept = this.accept || 'images/*';
                    _file.multiple = false;
                    _file.onchange = function (e) {

                        if (_file.files.length > 0) {
                            var reader = new FileReader();
                            reader.onload = function (evt) {
                                var src = evt.target.result;
                                me.setSrc(src);
                            }
                            reader.readAsDataURL(_file.files[0]);
                            //设置文件对象
                            me.file = _file.files[0];
                            me.funApplyByIOC(me.onchange, [me, e]);
                        }
                    }
                    _add.title = "点击选择本地图片";
                    _add.appendChild(_file);
                }
                else {
                    _add.title = "点击选择素材库图片";
                    _add.onclick = function (evt) {
                        //选择图片后回调处理
                        me.selector.callback = function (item,e,config) { 
                                me.setValue(item.data["Url"]);
                            }; 
                        var _d = Rsd.create(me.selector.viewType||Rsd.app.imageSelectorViewType, me.selector); 
                        _d.parent = me;
                        _d.showDialog().load();
                    } 
                } 
            }

            this.ctrl.element.appendChild(_add);

        }

        //背景
        if (this.backgroundImage == false || this.backgroundImage == 'none') {
            this.ctrl.element.classList.add('x-control-image-none-bg');
        }
        else {
            this.ctrl.element.style.backgroundPosition = 'center';
            this.ctrl.element.style.backgroundSize = 'contain';
            this.ctrl.element.style.backgroundRepeat = 'no-repeat';
            this.ctrl.element.style.backgroundImage = this.backgroundImage;
        }
        //标签
    },
    /*
    *
    * */
    onAfterInit: function onAfterInit() {

        this.callParent();
        //必须在此设置src
        if(this.src)
        {
            this.setSrc(this.src);
        }
        if(this.value)
        {
            this.setValue(this.value);
        }

        if (this.clip) {
            this.image.style.clip = this.clip;
        } 

    },
    /**
     * 
     */
    showView:function showView(url)
    {
        var me = this;
        var _view = Rsd.create('Rsd.widget.ImageViewer', {title: me.title });

        _view.showDialog(document.body).loadData([{src: url||me.src, text: me.label.content}]);
    },
    /**
     * 
     */
    btn_view_image: function btn_view_image() {

        this.showView(this.value);
    },
    /**
     * 
     */
    btn_download_image: function btn_download_image() {
        if (this.image.src) {
            Rsd.downloadImage(this.image, this.getFileName());
            return;
        }

        Rsd.popup('图片未加载');
    },
    /**
     * 
     * @returns 
     */
    getFileName: function getFileName() {
        var filename = null;
        if (this.getFileNameHandler) {
            filename = this.funApplyByIOC(this.getFileNameHandler);
        }
        if (Rsd.isEmpty(filename)) {
            filename = Rsd.getFileName(this.src, false);
        }
        return filename;

    },
    /**
     * 
     */
    btn_seg_image: function btn_seg_image() {

        if(this.src.startWith("data:image/"))
        {
            Rsd.popup('图片先上传后，再抠图');
            return;
        }
        if(Rsd.isEmpty(this.showImageEditorHandler))
        {
            alert('showImageEditorHandler is null');
        }

        this.funApplyByIOC(this.showImageEditorHandler,[this]);
        
    },
    /*
     * 图片src 
     */
    setSrc: function (src) {

        var me = this;

        me.src = src;

        if (me.image) {
            me.image.style.display = 'none';
            if (me.showLoadingBar) {
                //多个图片布局在一个页面时 不适合使用 
                me.showLoading('加载中...', null);
            }

            setTimeout(function () {

                me.image.src = me.src;

            }, 20);

        }
 
        if (Rsd.isEmpty(me.src) || me.src == '#') {
            this.image.style.display = 'none';
            if (this.btnClose) {
                this.btnClose.style.display = 'none';
            }
 
            if (this.btnAdd) {
                this.btnAdd.style.display = 'inline-block';
            }
        }
        else 
        {

            this.image.style.display = 'inline-block';
            if (this.btnClose) {
                this.btnClose.style.display = 'inline-block';
            }
            if (this.btnAdd) {
                this.btnAdd.style.display = 'none';
            }

        }
    },
    /*
     * */
    getSrc: function () {
        return this.src;
    },
    /*
    * 一般为 图片src ，或是 图片src 格式化字符 预留部分
    */
    setValue: function setValue(value) {

        this.value = value;
        var me = this;

        if (Rsd.isEmpty(value) || value == 'null') {
            this.setSrc('#');
            return this;
        }
 
        if ((this.value && this.value.startWith('http://')) || Rsd.isEmpty(this.formatString)) {
            this.setSrc(this.value);
        }
        else {
            var _src = Rsd.formatTemplateString(this.formatString || '',{value:value});

            this.setSrc(_src);
        }
        return this;
    },
    /*
    * */
    getValue: function getValue() {
        return this.value;
    },
    /** 
     * 单文件上传 ，所以只有一个文件返回
    */
    getFile: function () {

        return this.file;
    },
    /*
    *
    * */
    makeControl: function makeControl(config, row) {
 
        var me = this;

        me.timer = (me.timer || 10) + 0;
        if (me.timer > 3000) {
            me.timer = 10;
        }
        var _config = config || {};
        //var _editable = _config.editable;
        var _value = row[_config.dataIndex || _config.name];
        var _h = _config.height || 'auto';
        var _w = _config.width || 50;
        var _ctrl = document.createElement('img');
        setTimeout(function () {
            var _src = '';
            if (_config.formatString ) {
                _src = Rsd.formatTemplateString(_config.formatString, row);
            } else {
                _src = _value;
            }

            var list = _src.split('http://');
            if (list.length > 2) {
                _ctrl.src = list[list.length - 1];
            } else {
                _ctrl.src = _src;
            }

        }, me.timer);

        if (_config.clip) {
            _ctrl.style.clip = _config.clip;
        }
    
        _ctrl.setAttribute("width",_w); 
        _ctrl.setAttribute("height",_h); 

        return [_ctrl];
    }

},function(type){

    var _toolbarGetter = function () {

        return this.___toolbar||{
            visible: false,
            buttons:[]
        };
    };

    var _toolbarSetter = function (value) {
        
        if(Rsd.isEmpty( this.___toolbar))
        {
            this.___toolbar = {
                visible: false,
                position: 'right',
                buttons: [
                    {
                        //@description 查看大图
                        name: 'zoom',
                        title: '查看大图',
                        svg: {
                            "viewBox": "0 0 1024 1024",
                            "path": "M959.369997 909.993104 697.933422 648.464427c-3.111-3.111-6.621109-5.577286-10.366589-7.419326 53.480547-62.834015 85.787874-144.22146 85.787874-232.997532 0-198.459291-161.505931-359.965222-360.006156-359.965222-198.459291 0-359.965222 161.505931-359.965222 359.965222 0 198.500225 161.505931 360.006156 359.965222 360.006156 83.44439 0 160.34954-28.541379 221.474551-76.383239 1.882974 4.287859 4.584632 8.299411 8.09474 11.80952l261.487743 261.487743c7.593296 7.583063 17.54031 11.379711 27.487323 11.379711 9.947013 0 19.883793-3.796648 27.477089-11.379711C974.597524 949.781158 974.597524 925.179697 959.369997 909.993104zM413.34855 725.850554c-175.239359 0-317.772283-142.563625-317.772283-317.802984S238.109191 90.275287 413.34855 90.275287 731.151535 232.808211 731.151535 408.04757 588.58791 725.850554 413.34855 725.850554z"
                        },
                        handler: 'btn_view_image'
                    },
                    {
                        name: 'download',
                        title: '下载图片',
                        svg: {
                            "viewBox": "0 0 1024 1024",
                            "paths":
                                [
                                    "M760.4736 493.9264a25.6 25.6 0 0 0-36.1984 0L512 706.2016V128a25.6 25.6 0 0 0-51.2 0v578.2016L248.5248 493.9264a25.6 25.6 0 0 0-36.1984 36.1984l256 256a25.4976 25.4976 0 0 0 36.2496-0.0512l256-256a25.6 25.6 0 0 0 0-36.1984z",
                                    "M896 972.8h-819.2C34.4576 972.8 0 938.3424 0 896v-102.4a25.6 25.6 0 0 1 51.2 0v102.4a25.6 25.6 0 0 0 25.6 25.6h819.2a25.6 25.6 0 0 0 25.6-25.6v-102.4a25.6 25.6 0 0 1 51.2 0v102.4c0 42.3424-34.4576 76.8-76.8 76.8z"
                                ]
                        },
                        handler: 'btn_download_image'
                    },
                    {
                        name: 'seg_image',
                        title: '图片美化',
                        svg:
                        {
                            "viewBox": "0 0 1024 1024",
                            "paths": [
                                "M487 413.9v-96.1c0-37.4-30.4-67.9-67.9-67.9H299c-37.4 0-67.9 30.4-67.9 67.9v96.1c0 5.1 1.7 10 4.9 13.9l24.2 29.8-25.1 35.3c-2.6 3.7-4.1 8.2-4.1 12.7v212.5c0 37.4 30.4 67.9 67.9 67.9 12.2 0 22-9.8 22-22s-9.8-22-22-22c-13.2 0-23.9-10.7-23.9-23.9V540.4H453.3c12.9 0 23.8-8.3 27.7-19.8 7-7.5 8-19.1 1.8-27.7l-25.1-35.3 24.2-29.8c3.3-4 5.1-8.9 5.1-13.9z m-188-120h120.1c13.2 0 23.9 10.7 23.9 23.9v47.1H275.1v-47.1c0-13.2 10.8-23.9 23.9-23.9zM443 406l-29.8 36.7c-6.2 7.7-6.6 18.6-0.9 26.6l8.9 12.5H297l8.9-12.5c5.7-8.1 5.4-19-0.9-26.6L275.1 406v-15.7H443V406zM680 669.3c-27.8 28.6-73.9 29.4-102.5 1.6-28.6-27.8-29.4-73.9-1.6-102.5 0 0 351.8-308.9 380.5-281.1C985 315 680 669.3 680 669.3zM447.5 672.3c15.6-12 64.7-19.9 92.4 6.4 24.5 23.3 28.5 50.6 23.8 81.3-12.2 79.7-88.7 80.7-138.5 77.2-29.3-2.1-99.8-8.1-99.8-8.1 22.1-14.2 33.3-17 68.9-76 12.5-20.8 20.4-55.5 53.2-80.8z",
                                "M765.2 915H170.7c-57.9 0-104.9-47.1-104.9-104.9V215.5c0-57.9 47.1-104.9 104.9-104.9h594.5c57.9 0 104.9 47.1 104.9 104.9v26.4c0 12.2-9.8 22-22 22s-22-9.8-22-22v-26.4c0-33.6-27.3-60.9-60.9-60.9H170.7c-33.6 0-60.9 27.3-60.9 60.9V810c0 33.6 27.3 60.9 60.9 60.9h594.5c33.6 0 60.9-27.3 60.9-60.9V642.9c0-12.2 9.8-22 22-22s22 9.8 22 22v167.2c0.1 57.8-47 104.9-104.9 104.9z"
                            ]
                        },
                        handler: 'btn_seg_image'
                    }
                ]
            }; 
        }
        if(Rsd.isEmpty(value))
        {
            this.___toolbar = {visible:false,buttons:[]};
            return;
        }
        if(Rsd.isBoolean(value))
        {
            this.___toolbar.visible= value;
            return;
        }

        this.___toolbar = Rsd.apply(this.___toolbar,value); 
    }

    this.defineProperty(type,"toolbar", _toolbarGetter, _toolbarSetter,false);
    this.defineProperty(type,"toolBar", _toolbarGetter, _toolbarSetter,false);

    var _selectorGetter = function () {

        if(!this.___selector)
        {
             this.___selector = { 
                        title: '图片选择',
                        mode: 'dialog',
                        closeBtn: true,
                        draggable: true,
                        readonly: false,
                        showCheckbox: true,
                        multiple: false, 
                        style:null, 
                        text:Rsd.lang('form.image.selector.chooseButtonText'),
                    };
        }

        return this.___selector;
    };

    var _selectorSetter = function (value) {
        
        if(Rsd.isEmpty(value))
        {
            this.___selector = null;
            return;
        }
        this.___selector = Rsd.apply(this.selector,value); 
    }

    this.defineProperty(type,"selector", _selectorGetter, _selectorSetter,false);
});

